package com.wayne.sqlSession;

import com.wayne.binding.MapperMethod;
import com.wayne.config.BoundSql;
import com.wayne.pojo.Configuration;
import com.wayne.pojo.MappedStatement;
import com.wayne.utils.GenericTokenParser;
import com.wayne.utils.ParameterMapping;
import com.wayne.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

  @Override
  public int update(Configuration configuration, MappedStatement mappedStatement, Object parameter) throws Exception {
    // 1、注册驱动，获取连接
    Connection connection = configuration.getDataSource().getConnection();
    PreparedStatement preparedStatement = preparedStatement(connection, mappedStatement, parameter);
    try {
      preparedStatement.execute();
    } catch (Exception e) {
      return 0;
    }
    return 1;
  }

  @Override
  public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object parameter) throws Exception {
    // 1、注册驱动，获取连接
    Connection connection = configuration.getDataSource().getConnection();
    PreparedStatement preparedStatement = preparedStatement(connection, mappedStatement, parameter);
    // 5、执行SQL
    ResultSet resultSet = preparedStatement.executeQuery();
    String resultType = mappedStatement.getResultType();
    Class<?> resultTypeClazz = getClassType(resultType);
    List<Object> resultList = new ArrayList<>();
    // 6、封装返回结果集
    while (resultSet.next()) {
      ResultSetMetaData metaData = resultSet.getMetaData();
      Object result = resultTypeClazz.newInstance();
      for (int i = 1; i <= metaData.getColumnCount(); i++) {
        String columnName = metaData.getColumnName(i);
        Object value = resultSet.getObject(columnName);

        // 使用反射或者内省
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClazz);
        Method writeMethod = propertyDescriptor.getWriteMethod();
        writeMethod.invoke(result, value);
      }
      resultList.add(result);
    }
    return (List<E>) resultList;
  }


  private PreparedStatement preparedStatement(Connection connection, MappedStatement mappedStatement, Object parameter) throws SQLException, NoSuchFieldException, IllegalAccessException {
    // 2、获取SQL 语句：select * from user where id=#{id} and username=#{username}
    // 转换SQL语句 ：select * from user where id = ? and username=? 转换的过程中，还需要对#{}里面的值进行解析存储
    String sql = mappedStatement.getSql();
    BoundSql boundSql = getBoundSql(sql);
    // 3、获取预处理对象：preparedStatement
    PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
    // 4、设置参数
    List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
    String parameterType = mappedStatement.getParameterType();
    Class<?> parameterTypeClazz = getClassType(parameterType);
    //非实体类
    if (parameter instanceof MapperMethod.ParamMap) {
      for (int i = 0; i < parameterMappingList.size(); i++) {
        preparedStatement.setObject(i + 1, ((MapperMethod.ParamMap) parameter).get(String.format("arg%s", i)));
      }
    } else {
      for (int i = 0; i < parameterMappingList.size(); i++) {
        ParameterMapping parameterMapping = parameterMappingList.get(i);
        String content = parameterMapping.getContent();
        // 反射
        Field declaredField = parameterTypeClazz.getDeclaredField(content);
        declaredField.setAccessible(true);
        Object value = declaredField.get(parameter);
        preparedStatement.setObject(i + 1, value);
      }
    }
    return preparedStatement;
  }

  private Class<?> getClassType(String classType) {
    try {
      if (classType != null) {
        return Class.forName(classType);
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 完成对#{}的解析工作：1、将#{} 使用?代替，2、解析出#{}里面的值进行存储
   *
   * @param sql
   * @return
   */
  private BoundSql getBoundSql(String sql) {
    ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
    GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
    // 解析出来的SQL
    String parseSQL = genericTokenParser.parse(sql);
    // #{}解析出来的参数名称
    List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
    return new BoundSql(parseSQL, parameterMappings);
  }

}
